import {z} from "zod";
import {ActionState} from "@/lib/zod/types";
import {getSession} from "@/lib/session";


export const safeAction = <F>(schema: z.Schema, callbak: (state: ActionState<F>,data:F, formData: FormData) => Promise<ActionState<F>>) => {

    return async (state: ActionState<F>, playload: FormData): Promise<ActionState<F>> => {

        const session = await getSession();
        if (!session) {
            return {
                code: 403,
                msg: "用户未登录",
            } as ActionState<F>;
        }
        const entries = Object.fromEntries(playload.entries());
        const schemaCheck = schema.safeParse(entries);
        if (!schemaCheck.success) {
            const errors = schemaCheck.error.flatten().fieldErrors;
            return {
                code: 402,
                msg: "参数校验失败",
                errors,
                input:{
                    ...entries
                }
            } as ActionState<F>;
        }
        let err = '';
        try {
            return callbak(state, schemaCheck.data, playload);
        }catch (e){
            err = e?.toString()||"";
        }
        return {
            code:500,
            msg:`系统异常${err}`
        };
    }
}